﻿using System;
using System.Linq;

namespace Outfish {

	/// <summary>
	/// Base class for various Document Object Model classes.
	/// </summary>
	public class WebDocument {
	
		public WebDocument(string source){
			if( source == null ){ throw new ArgumentNullException("source"); }
			this.Source = source;
		}
	
		/// <summary>Root node of the document</summary>
		public ContainerNode DocumentNode{ get; protected set; }
	
		/// <summary>
		/// The original string that generated the document.
		/// </summary>
		/// <remarks>
		/// Stored in here because nodes need (1) the string so they can parse, print, etc, (2) the Document
		/// 
		/// </remarks>
		public string Source{ get; private set; }
	
		/// <summary>
		/// Callback method activated when a node is added to the doucment tree.
		/// </summary>
		public Action<HtmlNode> NodeAdded;
	
		/// <summary>
		/// Finds the leafiest node that contains the given html index
		/// </summary>
		public HtmlNode FindNodeAt( int contentIndex ){
		
			HtmlNode cur = this.DocumentNode;
			if( !cur.Contains( contentIndex ) ){ return null; }
			
			while( true ){
				HtmlNode next = cur.ChildNodes.Where( c => c.Contains( contentIndex ) ).FirstOrDefault();
				if( next != null ){
					cur = next;
				} else {
					return cur;
				}
			}
		
		}
	
	
	}
}
